<template>
  <div class="progress-overview-page" v-loading="loading">
    <div class="left-container">
      <div class="item">
        <broken-line :options="actualDataOptions"></broken-line>
      </div>
      <div class="item output">
        <i class="el-icon-more" @click="$router.push('/progress/output')"></i>
        <h3 class="total" v-if="outputStatis.actualOut">总产值：{{ outputStatis.actualOut }} 万元</h3>
        <broken-line :options="outputConfig"></broken-line>
      </div>
      <div class="item warn">
        <div class="title">
          <h3 style="font-size: 18px;">进度预警</h3>
          <i class="el-icon-more" @click="$router.push('/progress/totality')"></i>
        </div>
        <ul>
          <li v-for="item in warnData" :key="item.id">
            <span class="name">{{ item.scheduleName }}</span>
            <div class="info">
              <span class="time">{{ item.modifyTime }}</span>
              <div class="day">
                <span v-if="item.startText" class="text" :style="{ background: item.startColorStr }">
                  {{ item.startText }}{{ item.startDay }}天
                </span>
                <span v-if="item.endText" class="text" :style="{ background: item.endColorStr }">
                  {{ item.endText }}{{ item.endDay }}天
                </span>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="main-container" v-loading="fileLoading">
      <div class="nav">
        <el-button size="small" :type="fileType === '1' ? 'primary' : ''" @click="handleChange('1')">航拍照片</el-button>
        <el-button size="small" :type="fileType === '3' ? 'primary' : ''" @click="handleChange('3')">日常照片</el-button>
      </div>
      <el-carousel class="carousel-container">
        <el-carousel-item v-for="item in fileList" :key="item.id">
          <img :src="$checkUrl(item.fileUrl)" alt="" />
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="right-container">
      <div class="item echarts">
        <div class="item-echarts">
          <echarts-base :options="progressOptions"></echarts-base>
        </div>
      </div>
      <div class="item milestone">
        <div class="title">
          <h3 style="font-size: 18px;">本月节点</h3>
          <i class="el-icon-more" @click="$router.push('/progress/milestone')"></i>
        </div>
        <ul>
          <li v-for="item in milepostList" :key="item.id" :style="{ background: item.colorStr }">
            <span class="name" :title="item.milepostName">
              <i :class="item.iconType" :style="{ color: item.iconColor }"></i>
              {{ item.milepostName }}
            </span>
            <span class="time">{{ item.planTime }}</span>
            <span class="status">
              {{ item.pointTimeDesc }}
            </span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import echartsBase from '@/components/echarts/base';
import brokenLine from '@/components/echarts/brokenLine';

export default {
  data() {
    return {
      fileType: '1',
      loading: false,
      // 进度占比
      progressData: {
        legend: [],
        data: []
      },
      // 进度预警
      warnData: [],
      // 产值情况
      outputData: {
        xAxisData: [],
        seriesData: []
      },
      // 产值统计
      outputStatis: {},
      // 本月节点
      milepostList: [],
      actualData: [],
      fileList: [],
      fileLoading: false
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    // 赢得值图表
    actualDataOptions() {
      const series = [{
        name: '费用偏差（CV）',
        data: []
      }, {
        name: '进度偏差（SV）',
        data: []
      }, {
        name: '费用绩效指数（CPI）',
        data: []
      }, {
        name: '进度绩效指标（SPI）',
        data: []
      }];
      const xAxisData = [];
      this.actualData.forEach(item => {
        const { cv, cpi, monthOut, sv, spi } = item;
        xAxisData.push(monthOut);
        series[0].data.push(cv);
        series[1].data.push(sv);
        series[2].data.push(cpi);
        series[3].data.push(spi);
      });
      return {
        title: {
          text: '挣值分析（万元）',
          padding: [10, 0, 0, 10],
          textStyle: { color: '#fff' }
        },
        // legend: {
        //   textStyle: {
        //     color: '#fff',
        //     fontSize: this.$setRem(12, false)
        //   },
        //   right: 0,
        //   top: 30,
        //   data: series.map(item => item.name)
        // },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData,
          axisLine: { // 轴线
            show: false
          },
          axisTick: { // 刻度
            show: true
          },
          axisLabel: {
            color: '#bac4ff'
          }
        },
        series: series.map(item => {
          return {
            type: 'line',
            smooth: true,
            markLine: {
              lineStyle: {
                color: 'red',
                type: 'solid'
              }
            },
            ...item,
          };
        }),
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            minValueSpan: 3,
            zoomLock: false
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        }
      };
    },
    // 产值情况
    outputConfig() {
      return {
        title: {
          text: '产值统计（万元）',
          padding: [10, 0, 0, 10],
          textStyle: { color: '#fff' }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.outputData.xAxisData,
          axisLine: { // 轴线
            show: false
          },
          axisTick: { // 刻度
            show: true
          },
          axisLabel: {
            color: '#bac4ff'
          }
        },
        series: [
          {
            name: '产值统计',
            type: 'line',
            smooth: true,
            data: this.outputData.seriesData,
            areaStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(238, 51, 83, .9)'
              }, {
                offset: 1,
                color: 'rgba(4, 101, 231, .3)'
              }])
            },
            itemStyle: {
              normal: {
                color: 'rgba(238, 51, 83, .9)', // 改变折线点的颜色
                lineStyle: {
                  color: 'rgba(238, 51, 83, .9)' // 改变折线颜色
                }
              }
            },
            markLine: {
              lineStyle: {
                color: 'red',
                type: 'solid'
              }
            }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            minValueSpan: 3,
            zoomLock: false
          }
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          },
          formatter: function(val) { // 自定义浮层内容
            const { marker, name, value, seriesName } = val[0];
            return `${name}<br />${marker}${seriesName}: ${value}万元`;
          }
        },
        toolbox: {
          itemSize: 20,
          iconStyle: {
            color: 'red'
          },
          emphasis: {
            iconStyle: {
              color: '#bac4ff'
            }
          }
        }
      };
    },
    // 进度占比
    progressOptions() {
      return {
        title: {
          text: '进度占比（%）',
          textStyle: {
            color: '#fff'
          }
        },
        textStyle: {
          color: '#fff'
        },
        legend: {
          data: this.progressData.legend,
          bottom: 10,
          textStyle: {
            color: '#fff'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        series: [
          {
            name: '进度占比',
            type: 'pie',
            radius: '55%',
            label: {
              color: '#fff',
              formatter: '{b}: {d}%'
            },
            data: this.progressData.data,
            // itemStyle: {
            //   color: 'rgb(85, 201, 246)'
            // },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
    },
  },
  async created() {
    this.getFileList();
    this.loading = true;
    await Promise.all([
      this.getScheduleEarly(),
      this.getMilepostSet(),
      this.getGainChartStatistic(),
    ]);
    this.loading = false;
  },
  components: {
    echartsBase,
    brokenLine
  },
  methods: {
    // 切换tab
    handleChange(type) {
      this.fileType = type;
      this.getFileList();
    },
    setWarnData(data = []) {
      const checkDay = (day) => {
        if (Number(day) === 0) return 'green';
        if (day > 15) return 'red';
        if (day <= 5) return '#9c9c24';
        return 'orange';
      };
      this.warnData = data.map(item => {
        const { endEarly, startEarly } = item;
        const [startStatus, startDay] = endEarly ? startEarly.split(':') : [];
        const [endStatus, endDay] = endEarly ? endEarly.split(':') : [];
        const startText = startStatus === '1' ? '开始逾期' : '';
        const endText = endStatus === '1' ? '结束逾期' : '';
        const startColorStr = checkDay(startDay);
        const endColorStr = checkDay(endDay);
        return {
          ...item,
          startText,
          endText,
          startColorStr,
          endColorStr,
          startDay,
          endDay
        };
      });
    },
    setOutputData(data = []) {
      const result = {
        xAxisData: [],
        seriesData: []
      };
      Array.isArray(data) && data.forEach(item => {
        const { monthOut, actualOut } = item;
        result.xAxisData.push(monthOut);
        result.seriesData.push(actualOut);
      });
      this.outputData = result;
    },
    // 获取进度预警/进度占比
    async getScheduleEarly() {
      const { success, data: { data }} = await this.$Model.getScheduleEarly({
        projectId: this.projectId
      });
      if (success && data) {
        const scheduleRatio = data.scheduleRatio || {};
        const warnData = data.scheduleEarlyChartStatistic || [];
        this.setWarnData(warnData);
        const type = {
          finishPercent: '已完成',
          unFinishPercent: '未完成'
        };
        const keys = Object.keys(type);
        this.progressData = {
          legend: keys.map(key => type[key]),
          data: keys.map(key => {
            const value = scheduleRatio[key]
              ? scheduleRatio[key].replace('%', '')
              : '';
            return {
              name: type[key],
              value: isNaN(value) ? 0 : Number(value)
            };
          })
        };
      }
    },
    // 获取本月节点
    async getMilepostSet() {
      const { success, data: { data }} = await this.$Model.getMilepostSet({
        projectId: this.projectId
      });
      if (success && data) {
        const milepostSet = data.milepostSet || [];
        // 未完成（1: 已超节点，2: 距今还有) 完成（3：正常完成: 4：超时，5：提前）
        const setColor = (status, day) => {
          const result = {
            colorStr: 'rgba(0, 128, 0, .5)',
            iconType: 'el-icon-success',
            iconColor: 'green'
          };
          if (!day) return result;
          switch (status) {
            case '3':
            case '4':
            case '5': return result;
            case '1':
            case '2':
              if (day <= 5) {
                result.colorStr = 'rgba(255, 255, 0, .5)';
                result.iconType = 'el-icon-warning';
                result.iconColor = 'yellow';
              } else if (day > 15) {
                result.colorStr = 'rgba(255, 0, 0, .5)';
                result.iconType = 'el-icon-error';
                result.iconColor = 'red';
              }
              return result;
            default: return result;
          }
        };
        this.milepostList = milepostSet.map(item => {
          const { pointTimeFlag, pointTimeDesc } = item;
          const day = pointTimeDesc.replace(/[^\d+]/g, '');
          return {
            ...item,
            ...setColor(pointTimeFlag, day)
          };
        });
      }
    },
    // 获取赢得值图表/进度产值
    async getGainChartStatistic() {
      const { success, data: { data }} = await this.$Model.getGainChartStatistic({
        projectId: this.projectId
      });
      if (success && data) {
        const { gainChartStatistic, statis } = data;
        this.actualData = gainChartStatistic || [];
        this.setOutputData(gainChartStatistic);
        this.outputStatis = statis || {};
      }
    },
    // 获取文件信息
    async getFileList(hasInit = false) {
      this.fileLoading = true;
      const { success, data: { data }} = await this.$Model.getScheduleFile({
        pageNum: 1,
        pageSize: 10,
        fileType: this.fileType,
        projectId: this.projectId
      });
      this.fileLoading = false;
      if (success && data) {
        this.fileList = data.list || [];
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import "../../../assets/styles/main";

  .progress-overview-page {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    background-color: $mainBg;
    .left-container {
      width: calc(25% - 4px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background-color: $baseBg;
      .item {
        width: 100%;
        height: calc(33.3% - 5px);
        background: url("../../../assets/images/overview/panel2.png") no-repeat center;
        background-size: 100% 101%;
        position: relative;
        .total {
          position: absolute;
          right: 20px;
          top: 30px;
        }
        &.output {
          .el-icon-more {
            position: absolute;
            top: 10px;
            right: 20px;
            font-size: 28px;
            cursor: pointer;
            color: $mainColor;
            z-index: 8;
          }
        }
        &.warn {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 10px 20px;
          .title {
            width: 100%;
            height: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            i {
              font-size: 28px;
              cursor: pointer;
              color: $mainColor;
            }
          }
          ul {
            width: 100%;
            height: calc(100% - 40px);
            overflow: auto;
            li {
              width: 100%;
              height: 75px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 10px;
              margin-bottom: 15px;
              background: url("../../../assets/images/overview/panel_border2.png") no-repeat left center;
              background-size: 100% 105%;
              color: #fff;
              .name {
                flex: 1;
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-size: 20px;
                font-weight: bold;
              }
              .info {
                width: 200px;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: flex-end;
                .time {
                  font-size: 12px;
                }
                .day {
                  width: 300px;
                  margin-top: 10px;
                  margin-right: -5px;
                  display: flex;
                  justify-content: flex-end;
                  align-items: center;
                  .text {
                    padding: 2px 8px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border-radius: 10px;
                    font-size: 12px;
                    color: #ddd;
                    transform: scale(.9);
                  }
                }
              }
            }
          }
        }
      }
    }
    .main-container {
      width: 50%;
      height: 100%;
      position: relative;
      background: url("../../../assets/images/overview/panel2.png") no-repeat;
      background-size: 100% 100%;
      background-position: center;
      padding: 6px;
      .nav {
        height: 40px;
        position: absolute;
        right: 10px;
        bottom: 10px;
        display: flex;
        align-items: center;
        z-index: 8;
      }
      .carousel-container {
        width: 100%;
        height: 100%;
        background: linear-gradient(0deg, rgb(246, 250, 255) 10%, rgb(214, 224, 235) 70%);
        border-radius: 10px;
        /deep/ .el-carousel__container {
          width: 100%;
          height: 100%;
          .el-carousel__item, img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .right-container {
      width: calc(25% - 4px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background-color: $baseBg;
      .item {
        width: 100%;
        height: calc(33.3% - 5px);
        background: url("../../../assets/images/overview/panel2.png") no-repeat center;
        background-size: 100% 101%;
        &.milestone {
          width: 100%;
          height: 66.5%;
          padding: 10px 20px;
          .title {
            width: 100%;
            height: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            i {
              font-size: 28px;
              cursor: pointer;
              color: $mainColor;
            }
          }
          ul {
            width: 100%;
            height: calc(100% - 40px);
            overflow: auto;
            li {
              width: 100%;
              height: 60px;
              display: flex;
              align-items: center;
              justify-content: space-between;
              font-size: 14px;
              color: #fff;
              padding: 0 10px;
              margin-bottom: 15px;
              .time {
                width: 100px;
                margin-right: 5px;
              }
              .status {
                width: 120px;
                text-align: right;
              }
              .name {
                width: calc(100% - 225px);
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                i {
                  font-size: 18px;
                  vertical-align: middle;
                }
              }
            }
          }
        }
        &.echarts {
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 10px 10px;
          .item-echarts {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
</style>
